package com.micromsg.basic.msg.controller;

import com.micromsg.basic.msg.pojo.MessagePayload;
import com.micromsg.basic.sys.dao.MessageMapper;
import com.micromsg.basic.sys.model.Message;
import com.micromsg.common.constant.CommonConstant;
import com.micromsg.common.util.IdGen;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
public class WsMessageController {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Resource
    MessageMapper messageMapper;

    @MessageMapping("/sendMessage")
    public void sendMessage(@Payload MessagePayload payload) {
        String receiverId = payload.getReceiverId();
        String senderId = payload.getSenderId();
        Date sendTime = new Date();
        // 处理接收到的消息
        // 存储消息到数据库等操作

        payload.setSenderInfo(payload.getSenderNickname() + " " + DateFormatUtils.format(sendTime, "yyyy/M/d HH:mm:ss"));
        messagingTemplate.convertAndSendToUser(senderId, "/messages", payload);

        payload.setSenderInfo(payload.getReceiverNickname() +" " + DateFormatUtils.format(sendTime, "yyyy/M/d HH:mm:ss"));
        payload.setSenderId("server");

        //System.out.println("payload：" + payload);

        Message message = new Message();
        BeanUtils.copyProperties(payload, message);
        message.setId(IdGen.next());
        message.setSendTime(sendTime);
        message.setSend(CommonConstant.YES);//CommonConstant.YES
        //messageMapper.insert(message);

        payload.setContent("回复：" + payload.getContent());
        // 发送消息给指定用户
        messagingTemplate.convertAndSendToUser(senderId, "/messages", payload);
    }

    @RequestMapping(value = "/loadMessage/{senderId}/{receiverId}", method = RequestMethod.GET)
    public List<Message> loadMessage(@PathVariable("senderId") String senderId, @PathVariable("receiverId") String receiverId) {
        List<Message> message = messageMapper.findMessage(senderId, receiverId);
        return message;
    }
}
